package com.ljb.utilslibrary.commUtils;

import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;


/**
 * 单例的Toast
 * Created by lijianbin on 2016/10/12.
 */
public class T {

    private static Toast t;

    private T() {
    }

    /**
     * 显示Toast
     *
     * @param c       上下文
     * @param message 文本
     */
    public static void showToast(final Context c, final String message) {
        if (ThreadUtils.isOnUIThread()) {
            showUIToast(c, message);
        } else {
            ThreadUtils.excuteOnUIThread(new Runnable() {
                @Override
                public void run() {
                    showUIToast(c, message);
                }
            });
        }
    }

    /**
     * 可以设置显示区域,文字大小的Toast
     *
     * @param c       上下文
     * @param message 文本内容
     * @param gravity 权重
     * @param xOffset x轴方向的偏移量
     * @param yOffset y轴方向的偏移量
     * @param unit    COMPLEX_UNIT_PX,
     *                TypedValue.COMPLEX_UNIT_DIP,
     *                COMPLEX_UNIT_SP,
     * @param size    文字大小
     */
    public static void showToast(final Context c, final String message, final int gravity, final int xOffset, final int yOffset, final int unit, final float size) {
        if (ThreadUtils.isOnUIThread()) {
            showUIToast(c, message, gravity, xOffset, yOffset, unit, size);
        } else {
            ThreadUtils.excuteOnUIThread(new Runnable() {
                @Override
                public void run() {
                    showUIToast(c, message, gravity, xOffset, yOffset, unit, size);
                }
            });
        }
    }

    //已确定为UI线程的Toast
    private static void showUIToast(Context c, String message) {
        if (t == null) {
            t = Toast.makeText(c, message, Toast.LENGTH_SHORT);
        } else {
            t.setText(message);
        }
        t.show();
    }

    //已确定为UI线程的Toast
    private static void showUIToast(Context c, String message, int gravity, int xOffset, int yOffset, int unit, float size) {
        if (t == null) {
            t = Toast.makeText(c, message, Toast.LENGTH_SHORT);
            t.setGravity(gravity, xOffset, yOffset);
            TextView tv = (TextView) t.getView().findViewById(android.R.id.message);
            tv.setTextSize(unit, size);
        } else {
            t.setText(message);
        }
        t.show();
    }
}
